from pyson.gen import PysonObject, string, struct
from pyduct.handlers import CookieFragmentBuilder, ProjectEntryFragmentBuilder, classOf, NONE, MessageFragment
from scaladuct.l10n import PropertyMeta, HintMeta
from chloroform.l10n import ProjectEntrySafeMetaData

class CommonMetaData(PysonObject):
    title = string("")
    description = string("")
    icon = string("")

class CommonMetaDataHolder(PysonObject):
    CommonMetaData = struct(CommonMetaData)

class AbstractCommonMetaDataBuilder(CookieFragmentBuilder):

    def getCookieMessageFragmentClass(self, cookieGateway, property):
        mtdSourceOpt = cookieGateway.pageExtension(classOf("scaladuct.l10n.HasHintsMetaDataSource"))
        if mtdSourceOpt is not NONE:
            source = mtdSourceOpt.get()

            mtd = self.createMetaData(source, cookieGateway.locale(), property)
            class Fragment(CommonMetaDataHolder, MessageFragment):

                def __init__(self):
                    super(Fragment, self).__init__()
                    self.CommonMetaData.title = mtd.title(property.name())
                    self.CommonMetaData.description = mtd.description("")

            return Fragment
        else:
            return None

    def createMetaData(self, source, locale, property): pass

class CommonMetaDataBuilder(AbstractCommonMetaDataBuilder):
    def createMetaData(self, source, locale, property):
        return PropertyMeta(source, locale, property)

class HintCommonMetaDataBuilder(AbstractCommonMetaDataBuilder):
    def createMetaData(self, source, locale, hint):
        return HintMeta(source, locale, hint)


class ProjectEntryMetaDataBuilder(ProjectEntryFragmentBuilder):
    def getProjectEntryFragmentClass(self, buildContext, projectEntry):
        project = buildContext.projectGateway
        mtdSourceOpt = project.extension(classOf("chloroform.l10n.ProjectMetaDataSource"))
        if mtdSourceOpt is not NONE:
            source = mtdSourceOpt.get()

            mtd = self.createMetaData(source, projectEntry, project.locale())
            class Fragment(CommonMetaDataHolder, MessageFragment):

                def __init__(self):
                    super(Fragment, self).__init__()
                    self.CommonMetaData.title = mtd.title().get()
                    self.CommonMetaData.description = mtd.description().get()

            return Fragment
        else:
            return None

    def createMetaData(self, source, entry, locale):
        return ProjectEntrySafeMetaData(source, entry, entry.name(), locale)


def getBuilders():
    return (CommonMetaDataBuilder,)

def getHintBuilders():
    return (HintCommonMetaDataBuilder,)

def getProjectEntryBuilders():
    return (ProjectEntryMetaDataBuilder,)